package org.cfk.delaytasktutorial.example;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.cfk.delaytasktutorial.annotation.LazyJob;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class CacheCleanupTask {

    public static final String WORKER_NAME = "cache_cleanup_task";

    @Data
    public static class CacheCleanupParam {
        private String cacheKey;
        private String cacheType; // 缓存类型，如：user_info, product_info等
        private LocalDateTime expireTime;
        private boolean forceClean; // 是否强制清理，忽略过期时间
    }

    @LazyJob(WORKER_NAME)
    public void cleanupCache(CacheCleanupParam param) {
        log.info("开始清理缓存，键：{}，类型：{}，过期时间：{}",
                param.getCacheKey(), param.getCacheType(), param.getExpireTime());
        
        try {
            // 1. 检查缓存是否需要清理
            if (!param.isForceClean() && 
                LocalDateTime.now().isBefore(param.getExpireTime())) {
                log.info("缓存{}尚未过期，无需清理", param.getCacheKey());
                return;
            }
            
            // 2. 执行缓存清理
            Thread.sleep(150); // 模拟Redis操作延迟
            log.info("已清理缓存：{}，类型：{}", 
                    param.getCacheKey(), param.getCacheType());
            
            // 3. 记录清理日志
            Thread.sleep(50); // 模拟写入日志延迟
            log.info("缓存清理日志已记录，键：{}，时间：{}", 
                    param.getCacheKey(), LocalDateTime.now());
            
        } catch (InterruptedException e) {
            log.error("缓存清理失败：{}", param.getCacheKey(), e);
            Thread.currentThread().interrupt();
            throw new RuntimeException("清理缓存失败", e);
        }
    }
}